import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Modal, message} from 'antd';
import {
    FORM_OPTIONS,
    TABLE,
    PAGINATION_OPTIONS,
    PAGE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT
} from '../constants';
import {formatAmount, conventEnumValueToString} from '../utils';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from './utils';
import {getAccountBalance} from './api';
import styles from './style.css';
const FormItem = Form.Item;
import {currency} from '../Enum';

class BalanceSelectPanel extends PureComponent {
    state = {
        dealerCode: this.props.dealerCode,
        dealerName: this.props.dealerName,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        isFetching: false,
        data: {},
        message: '',
        currentCondition: {}
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        getAccountBalance(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        if(!this.state.dealerCode) {
            message.warning(this.props.intl.formatMessage({
                id: 'validator.message.queryRequired',
                defaultMessage: '查询条件必填!'
            }));
            return;
        }
        const condition = {
            dealerCode: this.state.dealerCode,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'balanceSelectPanel.column.branchCode',
                    defaultMessage: '营销分公司编号'
                }),
                dataIndex: 'branchCode',
                sorter: true
            }, {
                title: this.props.intl.formatMessage({
                    id: 'balanceSelectPanel.column.vehicleSalesOrgCode',
                    defaultMessage: '销售组织编号'
                }),
                dataIndex: 'vehicleSalesOrgCode',
                sorter: true,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'balanceSelectPanel.column.currency',
                    defaultMessage: '资金类型'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'balanceSelectPanel.column.accountBalance',
                    defaultMessage: 'SAP余额'
                }),
                dataIndex: 'accountBalance',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'balanceSelectPanel.column.occupationBalance',
                    defaultMessage: '参考备货占用金额'
                }),
                dataIndex: 'occupationBalance',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'balanceSelectPanel.column.availableBalance',
                    defaultMessage: '参考可用金额'
                }),
                dataIndex: 'availableBalance',
                render: text => formatAmount(text)
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        
        return (
            <Modal
                title={formatMessage({
                    id: 'balanceSelectPanel.show.dealerQuery',
                    defaultMessage: '查询备件资金账户'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem required label={formatMessage({
                            id: 'balanceSelectPanel.show.dealerCode',
                            defaultMessage: '总代编号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="dealerCode"
                                disabled
                                value={`${'('}${this.state.dealerCode}${')'}${this.state.dealerName}`}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'balanceSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />
            </Modal >
        );
    }
}

BalanceSelectPanel.propTypes = {
    dealerCode: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    onCancel: PropTypes.func
};
import {injectIntl} from './intl';
export default injectIntl(BalanceSelectPanel);
